package com.ch.fastbuilder.common;

import java.text.MessageFormat;

import javax.sql.DataSource;

public class DataSourceUtil {
	private static String DEFAULT_DATA_SOURCE1 = "dataSource";
	private static String DEFAULT_DATA_SOURCE2 = "masterDataSource";
	private static String NOT_FOUND_BEAN_ERROR = "无法获取到bean id为{0}的数据源，请检查！";
	private static String NOT_FOUND_DATASOURCE_ERROR = "请配置默认的数据库连接池，bean id必须为dataSource或者defaultDataSource，请检查！";
	
	public static DataSource getDataSource() {
		Object bean = null;
		if(SpringContextUtil.containsBean(DEFAULT_DATA_SOURCE1)) {
			bean = SpringContextUtil.getBean(DEFAULT_DATA_SOURCE1);
		}
		
		if(bean == null && SpringContextUtil.containsBean(DEFAULT_DATA_SOURCE2)) {
			bean = SpringContextUtil.getBean(DEFAULT_DATA_SOURCE2);
		}
		
		if(bean == null) 
			throw new RuntimeException(NOT_FOUND_DATASOURCE_ERROR);
		
		return (DataSource)bean;
	}
	
	/**
	 * @return ApplicationContext
	 */
	public static DataSource getDataSource(String dataSourceName) {
		if(!SpringContextUtil.containsBean(dataSourceName)) 
			throw new RuntimeException(MessageFormat.format(NOT_FOUND_BEAN_ERROR, dataSourceName));
		
		Object bean = SpringContextUtil.getBean(dataSourceName);
		if(bean == null) 
			throw new RuntimeException(MessageFormat.format(NOT_FOUND_BEAN_ERROR, dataSourceName));
		
		return (DataSource)bean;
	}
}
